<?php
namespace control;
/*
*总账类
*/

use DateInterval;
use DatePeriod;

class accountTotalClass extends adIndexClass
{
	private const page       = 'accountTotal';
	private const title      = '总账';
	public const  typeOption = ['期初金额', '本期合计', '本年累计'];
	public static bool $isFormat = false;//是否格式化数字

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $maxDate = accountDetailsClass::getMaxDate();
        $minDate = accountDetailsClass::getMinDate();
        //生成查询表单
        $boucher = new voucherStatisticsClass();
        $html = $this->tableShow([
            [
                [
                    "会计期间" => text(array(
                        "name" => "createTime",
                        'value' => static::rGet(self::$stid .self::$coid. 'SearchMonth') ?: date('Y-m',strtotime($maxDate)) . ' ~ ' . date('Y-m',strtotime($maxDate)),
                        'laydate' => ['type' => 'month','range'=>'~','min'=>"'{$minDate}'",'max'=>"'{$maxDate}'"]
                    )),
                    '科目'  => componentClass::customSubject(['name' => 'formSubjectId','title' => '请选择']) . "-\n" .
                        componentClass::customSubject(['name' => 'toSubjectId','title' => '请选择']),
                ]
            ]
        ],1).$boucher->style();
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }


	/*列表-查询条件*/
	public function home()
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
		//返回
		return $this->homeFun($this->searchExecute([
            'html'         => $html,
            'layout'       => 'pop',
            'toolButton'   => $button,
            'searchOption' => '{}',
            'option' => '{fixed:true, row:1}'
        ]));
	}

	/*客户列表-查询结果*/
	public function homeSearch()
	{
        static::rSet(self::$stid .self::$coid. 'SearchMonth', $this->post('createTime'));;
		$detail = new accountDetailsClass();
		//like查询数组
		$like = array();
		//全等查询数组
		$equal       = array(
			'a.isTemplate' => '否',
			'a.coid'       => self::$coid,
		);
		$subjectText = '所有';

		$and = "";
		if ($this->post('formSubjectId')) {
			$subjectSearch = query('subject', "id = '" . $this->post('formSubjectId') . "'");
			$subjectText   = $subjectSearch['code'] . $subjectSearch['name'];
			$toSubject     = query('subject', "id = '" . $this->post('toSubjectId') . "'");
			if ($toSubject['id']) {
				$subjectText .= "-" . $toSubject['code'] . $toSubject['name'];
			}
			$subjectObj   = new subjectClass();
			$subjectIdArr = $subjectObj->getFromToSubject($this->post('formSubjectId'), $this->post('toSubjectId'));
			$and          .= " and b.subjectId in ('" . implode("','", $subjectIdArr) . "')";
		}
        $arr        = $this->post('createTime') ? explode('~', $this->post('createTime')) : [date('Y-m', strtotime(accountDetailsClass::getMinDate())), date('Y-m', strtotime(accountDetailsClass::getMaxDate()))];
		$arr[0] = trim($arr[0]);
		$arr[1] = trim(end($arr));
		//获取查询结果
		$where        = search(array("like" => $like, "=" => $equal)) . $and . " ";
		$subjectWhere = search(array(
			'=' => array(
				'coid' => self::$coid,
				'id'   => $this->post('subjectId'),
			),
		));
		if ($this->post('formSubjectId')) {
			$subjectIdArr = $subjectIdArr ?? [];
			$subjectWhere .= " and id in ('" . implode("','", $subjectIdArr) . "')";
		}
		$page = $this->page(array('table' => "subject", 'where' => $subjectWhere . " and (id in (select distinct subjectId from voucher as a join voucher_detail as b on a.id= b.orderId where 1=1 " . $where . voucherClass::joinWhere() . ") or initMoney !=0)", 'field' => "id", "order" => "code asc"));
		static::rSet(self::$stid . self::page . 'sql', $page['fullSql']);
		static::rSet(self::$stid . self::page . 'time', $this->post('createTime'));
		//获取表头
		$tr                            = '';
		accountDetailsClass::$isFormat = true;
		self::$isFormat                = true;
		foreach ($page['array'] as $array) {
			if (static::total(array('table' => 'subject', 'where' => "pid = '$array[id]' and coid = '" . self::$coid . "'")) > 0) {
				continue;
			}
			$subject = query('subject', "id = '$array[id]'");

			$start = new \DateTime($arr[0] . '-01');
			$end   = new \DateTime($arr[1] . '-01');
			$end->modify('+1 month');
			$interval = DateInterval::createFromDateString('1 month');
			$period   = new DatePeriod($start, $interval, $end);
			foreach ($period as $k => $dt) {
				foreach (self::typeOption as $classify) {
					$month = $dt->format("Y年m月");
					if ($k > 0 && $classify == '期初金额') {
						continue;
					}
					switch ($classify) {
						case '期初金额':
							$result = $detail->initMoney($subject['id'], $dt->format("Y-m"));
							$tr     .= <<<eof
                    <tr>
                        <td>{$subject['code']}</td>
                        <td>{$subject['name']}</td>
                        <td>$month</td>
                        <td>$classify</td>
                        <td>{$result['jieMoney']}</td>
                        <td>{$result['daiMoney']}</td>
                        <td>{$result['jieBalance']}</td>
                        <td>{$result['daiBalance']}</td>
                    </tr>
eof;
							break;
						case '本期合计':
							$result  = $detail->monthBalance($dt->format("Y-m"), $subject['id']);
							$balance = $this->balance($dt->format("Y-m"), $subject['id']);
							$tr      .= <<<eof
                    <tr>
                        <td>{$subject['code']}</td>
                        <td>{$subject['name']}</td>
                        <td>$month</td>
                        <td class="l-b-color">$classify</td>
                        <td>{$result['jieMoney']}</td>
                        <td>{$result['daiMoney']}</td>
                        <td>{$balance['jieBalance']}</td>
                        <td>{$balance['daiBalance']}</td>
                    </tr>
eof;
							break;
						case '本年累计':
							$balance      = $this->balance($dt->format("Y-m"), $subject['id']);
							$totalBalance = $detail->monthBalance($dt->format("Y-m"), $subject['id'], 'year');
							$tr           .= <<<eof
                    <tr>
                        <td>{$subject['code']}</td>
                        <td>{$subject['name']}</td>
                        <td>$month</td>
                        <td class="l-orange-color">$classify</td>
                        <td>{$totalBalance['jieMoney']}</td>
                        <td>{$totalBalance['daiMoney']}</td>
                        <td>{$balance['jieBalance']}</td>
                        <td>{$balance['daiBalance']}</td>
                    </tr>

eof;
							break;
					}
				}
			}
			$tr .= <<<eof
<tr><td colspan="8" style="background-color: #f2f2f2"></td></tr>
eof;
		}
        // 月份选择器
        $monthSelector = componentClass::monthSelector(implode('~',$arr));
		$html = <<<eof
<div class="finance-subject-head">科目：$subjectText {$monthSelector['button']}</div>
<table class="tableMany">
    <thead>
        <tr>
            <td>科目编码</td>
            <td>科目名称</td>
            <td>期间</td>
            <td>摘要</td>
            <td>借方</td>
            <td>贷方</td>
            <td>借方金额</td><td>贷方金额</td>
        </tr>
    </thead>
    <tbody>
       $tr
    </tbody>
</table>
eof;
        //返回
        $json['html'] = $page['hint'] .
            "<div class='acct-main-container'>
                <form name='listForm'>" .
                    $html .
                "</form>" .
                $monthSelector['html'].
            "</div>" .
            $page['button'] .
            clear;
		return json_encode($json, 320);
	}

	/**
	 * 计算余额
	 *
	 * @param $month
	 * @param $subjectId
	 * @return array
	 */
	public function balance($month, $subjectId): array
	{
		$subject = query('subject', "id = '$subjectId'");
		//期初金额
		$initMoney = $subject['initMoney'];
		$jieInit   = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借' and date_format(a.recordDate,'%Y-%m') <= '$month'" . voucherClass::joinWhere()));
		$daiInit   = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷' and date_format(a.recordDate,'%Y-%m') <= '$month'" . voucherClass::joinWhere()));
		if ($subject['direction'] == '借') {
			$jieInit['money'] += $initMoney;
		} else {
			$daiInit['money'] += $initMoney;
		}
		$jieInit['money'] = self::centToYuan($jieInit['money']);
		$daiInit['money'] = self::centToYuan($daiInit['money']);
		if ($jieInit['money'] > $daiInit['money']) {
			$jieBalance = $jieInit['money'] - $daiInit['money'];
			$daiBalance = 0;
		} else {
			$daiBalance = abs($jieInit['money'] - $daiInit['money']);
			$jieBalance = 0;
		}

		$result = ['jieBalance' => round($jieBalance, 2), 'daiBalance' => round($daiBalance, 2)];
		if (self::$isFormat) {
			$result = accountDetailsClass::formatArrayNumber($result);
		}
		return $result;
	}


	/**
	 * 导出
	 */
	public function exportData()
	{
		if (!$this->power(self::page, 'export')) {
			$_SESSION['warn'] = '你还没有导出的权限';
		} else {
			$detail = new accountDetailsClass();
			$tr     = [];
			$sql    = static::rGet(self::$stid . self::page . 'sql');
			$time   = static::rGet(self::$stid . self::page . 'time');
            $arr = $time ? explode(' ~ ', $time): [date('Y-m', strtotime(accountDetailsClass::getMinDate())), date('Y-m', strtotime(accountDetailsClass::getMaxDate()))];
			$arr[0] = trim($arr[0]);
			$arr[1] = trim(end($arr));
			$title  = array("科目编码", "科目名称", "期间", '摘要', '借方余额', '贷方余额');
			$result = self::sqlFind($sql);
			foreach ($result as $array) {
				if (static::total(array('table' => 'subject', 'where' => "pid = '$array[id]' and coid = '" . self::$coid . "'")) > 0) {
					continue;
				}
				$subject = query('subject', "id = '$array[id]'");
				$start   = new \DateTime($arr[0] . '-01');
				$end     = new \DateTime($arr[1] . '-01');
				$end->modify('+1 month');
				$interval = DateInterval::createFromDateString('1 month');
				$period   = new DatePeriod($start, $interval, $end);
				foreach ($period as $k => $dt) {
					foreach (self::typeOption as $classify) {
						$month = $dt->format("Y年m月");
						if ($k > 0 && $classify == '期初金额') {
							continue;
						}
						switch ($classify) {
							case '期初金额':
								$result = $detail->initMoney($subject['id'], $dt->format("Y-m"));
								$tr[]   = [$subject['code'], $subject['name'], $month, $classify, $result['jieMoney'], $result['daiMoney'], $result['jieBalance'], $result['daiBalance']];
								break;
							case '本期合计':
								$result  = $detail->monthBalance($dt->format("Y-m"), $subject['id']);
								$balance = $this->balance($dt->format("Y-m"), $subject['id']);
								$tr[]    = [$subject['code'], $subject['name'], $month, $classify, $result['jieMoney'], $result['daiMoney'], $balance['jieBalance'], $balance['daiBalance']];
								break;
							case '本年累计':
								$balance      = $this->balance($dt->format("Y-m"), $subject['id']);
								$totalBalance = $detail->monthBalance($dt->format("Y-m"), $subject['id'], 'year');
								$tr[]         = [$subject['code'], $subject['name'], $month, $classify, $totalBalance['jieMoney'], $totalBalance['daiMoney'], $balance['jieBalance'], $balance['daiBalance']];
								break;
						}
					}
				}
			}
			$text = $this->control['name'] . "导出了" . self::title;
			$this->logText(["type" => self::page, "text" => $text]);
			$this->excelOut($title, $tr, self::title . ".xlsx");
		}
		header("Location:" . getenv("HTTP_REFERER"));
		exit(0);
	}
}
